package com.xin.springcloudquartz.utils;

import com.xin.springcloudquartz.bean.MyBean;
import org.quartz.*;
import org.quartz.impl.triggers.CronTriggerImpl;

import java.text.SimpleDateFormat;

import java.util.Map;

public class MessageUtils {
    /**
     * 创建事件
     * key 随机数
     * cron 时间
     * Scheduler quartz调度工厂
     * args 传递参数集合
     * @param key
     * @param cron
     */
    public static void create(String key, String cron, Scheduler scheduler, Map<String,Object> map) throws SchedulerException {
        String event= (String) map.get("eventId");
        String date= (String) map.get("date");
        JobDataMap jobDataMap=new JobDataMap();
        jobDataMap.put("eventId",event);
        jobDataMap.put("date",date);
        JobDetail jobDetail= JobBuilder
                .newJob(MyBean.class)
                .withIdentity(key,"group1")
                .usingJobData(jobDataMap)
                .build();
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(key, "group1")
                .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                .build();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println("创建事件成功，执行时间为:"+format.format(scheduler.scheduleJob(jobDetail,cronTrigger)));
    }

    /**
     * 修改事件
     * @param eventId
     * @param cron
     * @param scheduler
     * @throws Exception
     */
    public static  void update(String eventId,String cron,Scheduler scheduler) throws Exception {
        TriggerKey triggerKey=new TriggerKey(eventId,"group1");
        CronTriggerImpl cronTrigger= (CronTriggerImpl) scheduler.getTrigger(triggerKey);
        cronTrigger.setCronExpression(cron);
        scheduler.rescheduleJob(triggerKey,cronTrigger);

    }

}
